from django.db.models.signals import pre_save
from django.dispatch import receiver
from django_currentuser.middleware import get_current_user
from frame_server.model import BaseModel

@receiver(pre_save)
def auto_set_base_fields(sender, instance, **kwargs):
    """
    自动设置 BaseModel 中的字段
    """
    # 只处理继承自 BaseModel 的模型
    if issubclass(sender, BaseModel):
        # 获取当前登录用户
        user = get_current_user()

        if not user.is_authenticated:
            user = None

        # 如果是新创建的对象且 createUser 为空，则设置
        if not instance.pk and (instance.createUserId_id is None):
            instance.createUserId = user
        
        instance.updateUserId = user

        # 如果 tenantId 为空，尝试从当前用户或上下文中获取
        if user and (instance.tenantId_id is None) and (user.tenantId_id is not None):
            instance.tenantId = user.tenantId
